import pandas as pd

def tokey(col_name, category, y):  # 定义写key的函数,比如产生 'X1=3|Y=1'
    return col_name + "=" + str(category) + "|Y=" + str(y)

df = pd.read_csv("../datas/bayes_lihang.txt")
lam = 1  # 拉普拉斯  平滑因子
P = {}  # 用于存储所有概率的字典
Y = df["Y"].value_counts().keys()  # 获取类别种类的list   Y = [1, -1]
col_names = df.columns.tolist()[:-1]  # 获取特征列名   x1,x2
#查找所有条件概率，进行存储
for y in Y:  # 遍历每个类别
    df2 = df[df["Y"] == y]  #
    p = (df2.shape[0] + lam) / (df.shape[0] + len(Y) * lam)  # 计算先验概率
    P[y] = p  # 将先验概率加入P
    for col_name in col_names:  # 遍历每个特征
        categorys = df2[col_name].value_counts().keys()  # 获取每个特征下特征值种类的list
        for category in categorys:  # 遍历每个特征值
            p = (df2[df2[col_name] == category].shape[0] + lam) / (
                        df2.shape[0] + len(categorys) * lam)  # 计算在某类别下，特征=某特征的条件概率
            P[tokey(col_name, category, y)] = p  # 将条件概率加到P
            # print()
print(P)
X = [2, "S"]
res = []  # 用于存储属于某一类别的后验概率
for y in Y:  # 遍历类别
    p = P[y]  # 获取先验概率
    for i in range(len(X)):  # 遍历特征
        p *= P[tokey(col_names[i], X[i], y)]  # 获取条件概率
    # print(p)
    res.append(p)  # 将后验概率加入res
print(res)

import numpy as np

print(Y[np.argmax(res)])  # 返回最大的后验概率对应的类别